// 云函数入口文件
const cloud = require('wx-server-sdk')
const Decimal = require('decimal.js')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();

// 创建集合云函数入口函数
exports.main = async (event, context) => {
    try {
        let {
            conditions
        } = event.data

        // 获取当前日期
        const now = new Date();
        // 本月
        const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
        const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59)

        // 上月
        const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1)
        const endOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59)

        let query = db.collection('memberList')

        let data = {}

        // 总数量
        const totalResult = await query.where({
            _openid: conditions._openid,
            role: conditions.role,
        }).count()

        // 本月新增数量
        const curMonthResult = await query.where({
            _openid: conditions._openid,
            role: conditions.role,
            createTime: db.command.gte(startOfMonth).and(db.command.lte(endOfMonth))
        }).count()

        // 查询会员/代理商/合作商家数据
        if (conditions.role != 2) {
            // 上月新增数量
            const lastMonthResult = await query.where({
                _openid: conditions._openid,
                role: conditions.role,
                createTime: db.command.gte(startOfLastMonth).and(db.command.lte(endOfLastMonth))
            }).count()

            // 在线人数
            const onLineResult = await query.where({
                _openid: conditions._openid,
                role: conditions.role,
                onLine: 1,
            }).count()

            const curMonthNum = new Decimal(curMonthResult.total);
            const lastMonthNum = new Decimal(lastMonthResult.total);

            // 新增比例
            let growth = ""

            if (lastMonthResult.total == 0) {
                growth = `${curMonthNum.times(100).toString()}%`
            } else {
                growth = `${curMonthNum.div(lastMonthNum).times(100).toFixed(2)}%`
            }

            data = {
                ...data,
                totalResult: totalResult.total,
                curMonthResult: curMonthResult.total,
                lastMonthResult: lastMonthResult.total,
                onLineResult: onLineResult.total,
                growth,
            }
        } else {
            // 今日
            let todayStart = new Date(now);
            todayStart.setHours(0, 0, 0, 0);
            let todayEnd = new Date(now);
            todayEnd.setHours(23, 59, 59, 999);

            // 本周
            const dayOfWeek = now.getDay(); // 0-6, 0代表周日
            let curWeekStart = new Date(now);
            curWeekStart.setHours(0, 0, 0, 0);
            curWeekStart.setDate(now.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1))
            let curWeekEnd = new Date(curWeekStart);
            curWeekEnd.setHours(23, 59, 59, 999);
            curWeekEnd.setDate(curWeekStart.getDate() + 6)

            // 今日新增
            const todayResult = await query.where({
                _openid: conditions._openid,
                role: conditions.role,
                createTime: db.command.gte(todayStart).and(db.command.lte(todayEnd))
            }).count()

            // 本周新增
            const curWeekResult = await query.where({
                _openid: conditions._openid,
                role: conditions.role,
                createTime: db.command.gte(curWeekStart).and(db.command.lte(curWeekEnd))
            }).count()

            data = {
                ...data,
                totalResult: totalResult.total,
                todayResult: todayResult.total,
                curWeekResult: curWeekResult.total,
                curMonthResult: curMonthResult.total,
            }
        }

        return {
            code: 200,
            msg: "操作成功",
            data
        }
    } catch (err) {
        return {
            code: 500,
            message: err.message
        }
    }
}